<?php
namespace App\Handlers\Sms;


use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Log;

class CropSms implements Sms
{
    private $appid;

    private $appsecret;

    private $apptoken;

    private $path;

    private $disk;

    public $expire_time;

       private $api_url = 'http://comm.ustc.edu.cn/api/v1';
    // private $api_url = 'http://106.14.95.97:8082/api/v1';

    public function __construct($appid = '', $appsecret = '')
    {
        $this->appid = $appid;
        $this->appsecret = $appsecret;
        $this->disk = Storage::disk('local');
        $local_path = storage_path() . DIRECTORY_SEPARATOR. 'app'. DIRECTORY_SEPARATOR. 'accesstoken';
        if(!is_dir($local_path)){ mkdir($local_path, 0777, true);}
        $this->path = 'accesstoken' . DIRECTORY_SEPARATOR . $this->appid.'.json';

    }

    public function getAppCode(){
        $url = $this->api_url . '/code?appid='.$this->appid;
//        \Log::debug('短信app token返回结果：', [$url]);

        $result = json_decode(HttpRequest::httpGet($url),TRUE);

        return $result;
    }

    public function getAppToken(){
        $app_code_json = $this->getAppCode();
        if($app_code_json['code'] == 0){
            $this->apptoken = md5($this->appsecret . $app_code_json['app_code']);
        }
    }

    public function getAccessToken1() {
        $url = $this->api_url . '/accesstoken?appid='.$this->appid.'&apptoken='.$this->apptoken;

        if(Cache::has('app_access_token')) {

            $result = Cache::get('app_access_token');

        } else {

            $result = json_decode(HttpRequest::httpGet($url),TRUE);

//            \Log::debug('短信access_token返回结果：', [$result]);

             Cache::put('app_access_token',$result, 120);//缓存120分钟

        }

        return $result;
    }

    public function getAccessToken()
    {
        try {
            if(Cache::has('app_access_token')) {
                $result = Cache::get('app_access_token');
                if (!$result) {
                    $result = $this->setNewAccessToken();
                    return $result;
                }
                if ($result && is_array($result) && isset($result['expires_time'])) {
                    $expire_time = $result['expires_time'];
                    if(strtotime($expire_time) <= time()){
                        # 过期了，重新获取
                        $result = $this->setNewAccessToken();
                    }
                }
                return $result;
            } else {
                $result = $this->setNewAccessToken();
            }
        } catch (\Throwable $th) {
            $result = $this->setNewAccessToken();
        }
        return $result;
    }

    public function setNewAccessToken()
    {
        $url = $this->api_url . '/accesstoken?appid='.$this->appid.'&apptoken='.$this->apptoken;
        $result = json_decode(HttpRequest::httpGet($url),TRUE);
        Cache::put('app_access_token',$result, 10 * 60);//单位是秒，缓存30分钟
        return $result;
    }

    /**
     *
     * @param $data
     * @param string $access_token
     * @return mixed
     */
    public function postSms($data,$access_token='')
    {
        /**
         * post数据模板
         * {
        " messageTitle ": "消息标题",
        " messageContent ": "消息正文内容",
        " messageFromAddress ": "邮件发送使用的发件箱地址",
        " messageFromName ": "发送人署名",
        "is_plain_text ": "是否为纯文本",
        " request_sms_number_id ": "申请个人短信号id",
        " activity_id ": "主题id",
        " email_attachments_id ": "ID1,ID2,ID3",
        " messageSendTime": "消息发送时间",
        " messageTag":
        {
        "endDate":"ENDDATE"
        },
        " receiverRemoteUser":"USERID1,3|USERID2,5|USERID3,7",
        " receiverLocalUser": [
        {
        "userId":"USERID1",
        "userEmail":"EMAIL1",
        "userMob":"MOB1",
        "userWeixin":"1"
        },
        {
        "userId":"USERID2",
        "userEmail":"EMAIL2",
        "userMob":"MOB2",
        "userWeixin":"1"
        }
        ]
        }
         */
        $access_token = empty($access_token) ? $this->getAccessToken()['access_token'] : $access_token;

        $url = $this->api_url . '/message/sendall?appid='.$this->appid.'&access_token='.$access_token;

        $result = json_decode(HttpRequest::httpPost($url,$data),TRUE);

        return $result;
    }

    /**
     *消息附件上传接口
     * @param $data
     * @param string $access_token
     * @return mixed
     */
    public function postUploadfile($data,$access_token='')
    {
        /**
         * post数据模板
         * {
           "pathList": ["path1", "path2"]
            }
         */
        $access_token = empty($access_token) ? $this->getAccessToken()['access_token'] : $access_token;

        $url = $this->api_url . '/uploadfile?appid='.$this->appid.'&access_token='.$access_token;

        $result = json_decode(HttpRequest::httpPost($url,$data),TRUE);

        return $result;
    }
}